/*
 * Copyright (C) 2014 singwhatiwanna(任玉刚) <singwhatiwanna@gmail.com>
 *
 * collaborator:田啸,宋思宇,Mr.Simple
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ryg.dynamicload;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager.LayoutParams;

import com.android.volley.Response;
import com.aube.activity.WapActivity;
import com.aube.push.PushSetting;
import com.aube.utils.ForceLoginHelper;
import com.aube.video.PlayActivity;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.CanCloseLayout;
import com.huyn.baseframework.dynamicload.DLBridge;
import com.huyn.baseframework.dynamicload.OnShareChannelSelected;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.share.QQUtil;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareUtil;
import com.huyn.baseframework.share.WxUtil;
import com.huyn.baseframework.utils.AppUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.internal.DLAttachable;
import com.ryg.dynamicload.internal.DLIntent;
import com.ryg.dynamicload.internal.DLPluginManager;
import com.ryg.dynamicload.internal.DLProxyImpl;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;

public class DLProxyActivity extends Activity implements DLAttachable, DLBridge {

    protected DLPlugin mRemoteActivity;
    private DLProxyImpl impl = new DLProxyImpl(this);
    private ForceLoginHelper mLoginHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppUtil.setTranslucentStatus(this, true);
        if(!impl.onCreate(getIntent())) {
            Utils.showToast(this, "加载失败");
            finish();
        }
    }

    @Override
    public void attach(DLPlugin remoteActivity, DLPluginManager pluginManager) {
        mRemoteActivity = remoteActivity;
    }

    @Override
    public void reportDLUmengEvent(String label, String value) {
    }

    @Override
    public int startPluginActivityForResult(DLIntent dlIntent, int requestCode) {
        return DLPluginManager.getInstance(this).startPluginActivityForResult(this, dlIntent, DLProxyFragmentActivity.class, requestCode);
    }

    @Override
    public BlurViewDecorator getBlurView(boolean autoBlur) throws Exception {
        return BlurViewDecorator.createBlurView(this, autoBlur);
    }

    @Override
    public boolean isProxyUserLogin() {
        return isUserLogin();
    }

    @Override
    public void doProxyUserLogin() {
        doUserLogin();
    }

    @Override
    public void proxyLoginByChannel(int channel) {
        loginByChannel(channel);
    }

    @Override
    public void doProxyShare(ShareModule shareModule) {
        doShare(shareModule);
    }

    @Override
    public boolean isProxyWxInstalled() {
        return isWxInstalled();
    }

    @Override
    public void exeProxyHttpRequest(HashMap<String, String> params, Class modelClass, String TAG, Response.Listener listener) {
        exeHttpRequest(params, modelClass, TAG, listener);
    }

    @Override
    public View getProxyRootView() {
        return getRootView();
    }

    @Override
    public AssetManager getAssets() {
        return impl.getAssets() == null ? super.getAssets() : impl.getAssets();
    }

    @Override
    public Resources getResources() {
        return impl.getResources() == null ? super.getResources() : impl.getResources();
    }

    @Override
    public Theme getTheme() {
        return impl.getTheme() == null ? super.getTheme() : impl.getTheme();
    }

    @Override
    public ClassLoader getClassLoader() {
        return impl.getClassLoader();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mRemoteActivity != null)
            mRemoteActivity.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode,resultCode,data, QQUtil.getInstance(this).getBaseUiListener());
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onStart() {
        if (mRemoteActivity != null)
            mRemoteActivity.onStart();
        super.onStart();
    }

    @Override
    protected void onRestart() {
        if (mRemoteActivity != null)
            mRemoteActivity.onRestart();
        super.onRestart();
    }

    @Override
    protected void onResume() {
        if (mRemoteActivity != null)
            mRemoteActivity.onResume();
        super.onResume();
        Utils.releaseScreenLock(this);
    }

    @Override
    protected void onPause() {
        if (mRemoteActivity != null)
            mRemoteActivity.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mRemoteActivity != null)
            mRemoteActivity.onStop();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (mRemoteActivity != null)
            mRemoteActivity.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (mRemoteActivity != null)
            mRemoteActivity.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (mRemoteActivity != null)
            mRemoteActivity.onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (mRemoteActivity != null)
            mRemoteActivity.onNewIntent(intent);
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        if (mRemoteActivity != null)
            mRemoteActivity.onBackPressed();
        super.onBackPressed();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean result = super.onTouchEvent(event);
        if (mRemoteActivity != null)
            return mRemoteActivity.onTouchEvent(event);
        return result;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        boolean result = super.onKeyUp(keyCode, event);
        if (mRemoteActivity != null)
            return mRemoteActivity.onKeyUp(keyCode, event);
        return result;
    }

    @Override
    public void onWindowAttributesChanged(LayoutParams params) {
        if (mRemoteActivity != null)
            mRemoteActivity.onWindowAttributesChanged(params);
        super.onWindowAttributesChanged(params);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (mRemoteActivity != null)
            mRemoteActivity.onWindowFocusChanged(hasFocus);
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mRemoteActivity != null)
            mRemoteActivity.onCreateOptionsMenu(menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mRemoteActivity != null)
            mRemoteActivity.onOptionsItemSelected(item);
        return super.onOptionsItemSelected(item);
    }

    @Override
    public ComponentName startService(Intent service) {
        return super.startService(service);
    }

    @Override
    public void onClickToVideo(ChannelDetail channelDetail) {
        Intent intent = new Intent(this, PlayActivity.class);
        intent.putExtra(PlayActivity.CHANNEL_ITEM, channelDetail);
        startActivity(intent);
    }

    @Override
    public void onClickToVideo(ChannelDetail channelDetail, Category category) {
        Intent intent = new Intent(this, PlayActivity.class);
        intent.putExtra(PlayActivity.CHANNEL_ITEM, channelDetail);
        intent.putExtra(PlayActivity.CATEGORY_ITEM, category);
        startActivity(intent);
    }

    @Override
    public void onClickToWap(String title, String url, boolean post) {
        Intent intent = new Intent(this, WapActivity.class);
        intent.putExtra(WapActivity.WEB_TITLE, title);
        intent.putExtra(WapActivity.WEB_URL, url);
        intent.putExtra(WapActivity.WEB_POST, post);
        startActivity(intent);
    }

    @Override
    public void openPluginActivity(DLIntent intent) {
        DLPluginManager.getInstance(this).startPluginActivity(this, intent, DLProxyFragmentActivity.class);
    }

    @Override
    public boolean isUserLogin() {
        if(UserUtil.isUserLogin())
            return true;
        showLoginLayout();
        return false;
    }

    private void showLoginLayout() {
        if(getRootView() == null)
            return;
        if(mLoginHelper == null)
            mLoginHelper = new ForceLoginHelper(this);

        mLoginHelper.showLoginLayout();
    }

    @Override
    public void doUserLogin() {
        WxUtil.wxLoginRequest(this);
    }

    @Override
    public void loginByChannel(int channel) {

    }

    @Override
    public void doShare(ShareModule shareModule) {
        ShareUtil.startShare(this, shareModule);
    }

    @Override
    public void shareWeiboVideo(String url, String content, Bitmap bitmap) {

    }

    @Override
    public void shareWeiboImg(String path, String content) {

    }

    @Override
    public boolean isWxInstalled() {
        return ShareUtil.isWXAppInstalled();
    }

    @Override
    public void exeHttpRequest(HashMap<String, String> params, Class modelClass, String TAG, Response.Listener listener) {
        BFJSONRequest request = new BFJSONRequest(modelClass, params, listener);
        if(StringUtils.isNotBlank(TAG))
            request.setTag(TAG);
        HttpRequestLoader.getInstance(this).startHttpLoader(request);
    }

    @Override
    public View getRootView() {
        return mRemoteActivity != null ? mRemoteActivity.getRootView() : null;
    }

    @Override
    public void tooglePush() {
        if(PushSetting.isPushOn(this)) {
            PushSetting.unregistPush(this);
        } else {
            PushSetting.registPush(this);
        }
    }

    @Override
    public boolean isPushOn() {
        return PushSetting.isPushOn(this);
    }

    @Override
    public void showShareLayout(OnShareChannelSelected selector) {

    }

    @Override
    public void registToReceiveKeyBackGroup(CanCloseLayout layout) {
    }

    @Override
    public void onReady() {

    }

    public void reportUmengEvent(String id, String value) {
        if(StringUtils.isNotBlank(value))
            MobclickAgent.onEvent(this, id, value);
        else
            MobclickAgent.onEvent(this, id);
    }

    public void reportUmengEvent(String id) {
        MobclickAgent.onEvent(this, id);
    }

    public static String appendLabels(String... value) {
        if(value == null || value.length == 0)
            return "";
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<value.length; i++) {
            sb.append(value[i]);
            if(i != value.length-1)
                sb.append(",");
        }
        return new String(sb);
    }

}
